package com.ipfsemc.ipfsemc.service.imp;

import com.alibaba.druid.support.spring.stat.SpringStatUtils;
import com.ipfsemc.ipfsemc.controller.v1.ApplyController;
import com.ipfsemc.ipfsemc.mapper.*;
import com.ipfsemc.ipfsemc.model.*;
import com.ipfsemc.ipfsemc.service.IOrderService;
import com.ipfsemc.ipfsemc.util.CodecUtil;
import com.sun.org.apache.regexp.internal.RE;
import org.aspectj.weaver.ast.Or;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderServiceImpl implements IOrderService {
    private static final Logger logger = LoggerFactory.getLogger(ApplyController.class);

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private BountyMapper bountyMapper;

    @Autowired
    private UserSpaceMapper userSpaceMapper;

    @Autowired
    private LevelMapper levelMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public int addOrder(Order order) {
        //订单编号
        order.setOrderId(CodecUtil.createId());

        //记录订单数量
        String str;

        if (order.getOrderType() == 1) {
            str = order.getOrderSpecs() + "T/" + order.getDuration() + "年";
        } else {
            str = order.getOrderSpecs() + "份";
        }
        order.setProNum(str);

        /*用户微信付款   则是已付款    否则不需要执行下面*/
        if (null != order.getOrderState() && order.getOrderState() == 0) {
            order.setPayTime(new java.sql.Timestamp(System.currentTimeMillis()));

           if(order.getOrderType()!=4&&order.getOrderType()!=5){//4 服务费  5 续费
               //用户添加矿机
               int method = this.addMill(order);
               if (method != 1) {
                   logger.error("[order][addMill]添加矿机异常");
                   return -1;
               }
           }
        }
        return orderMapper.insertSelective(order);
    }

    /**
     * //添加用户矿机
     *
     * @param order
     * @return
     */
    private int addMill(Order order) {
        //添加用户矿机
        UserSpace userSpace = new UserSpace();
        if (order.getOrderType() != 4 && order.getOrderType() != 5) {//普通购买矿机  增加矿机
            //查询是否有上级  让上级获得相应的bounty利益
            int x = this.getBounty(order);
            if(x<0){
                logger.error("[order][getBounty]购买产品获取金豆异常");
                return -1;
            }

            userSpace.setUserId(order.getUserId());
            if (null != order.getDuration()) {
                if (order.getOrderType() == 2) {//表示如果是为6月为一租
                    userSpace.setDuration(order.getDuration() * 6);
                } else {//表示为海神 年
                    userSpace.setDuration(order.getDuration() * 12);
                }
            }
            userSpace.setProId(order.getProId());
            userSpace.setProType(order.getOrderType());
            userSpace.setSpace(order.getOrderSpecs());
            userSpace.setSpaceUp(order.getOrderUp());
            userSpace.setPayTime(order.getPayTime());
            //添加用户矿机
            int i = userSpaceMapper.insertSelective(userSpace);
            if (i <= 0) {
                logger.error("[order][insertSelective]添加用户矿机异常");
                return -1;
            }
        } else {
//            userSpace.setSpaceId(order.getSpaceId());
        }

        return 1;
    }

    /**
     * 查询是否有上级  让上级获得相应的Bounty(金豆)利益
     *
     * @param order
     * @return
     */
    private int getBounty(Order order) {
        int x = 1;
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(order.getUserId());
        BigDecimal b = null;
        BigDecimal bounty = null;
        int up;
        Product product = productMapper.selectProByKey(order.getProId());

        System.out.println(product);
        //让购买者自身获取金豆利益
        if (null != userInfo) {
            System.out.println("自身获取利益");
            b = new BigDecimal(userInfo.getRecomAward() / 100);
            UserInfo user = new UserInfo();
            bounty = order.getOrderPrice().multiply(b);
            user.setBounty(bounty);
            int i = addBounty(order.getProNum(), userInfo, bounty);
            if(i<0){
                logger.error("[order][addBounty]添加用户获得金豆记录异常");
                return -1;
            }
            up=product.getBuyUp()*order.getOrderSpecs();
            user.setSumUp(up);
            user.setUserId(order.getUserId());
            //判断是否达到升级的要求
            System.out.println(userInfo.getSumUp() + up);
            Integer m = this.upLevel(userInfo.getSumUp() + up, userInfo.getType());
            if(null!=m&&m!=-1){
                user.setLevelId(m);
            }
            int n = userInfoMapper.update(user);
            if (n<0){
                logger.error("[order][update]用户修改升力值以及等级异常");
                return -1;
            }
        }

        //通过用户查询是否有上级  让上级获得相应的Bounty(金豆)利益
        UserInfo applicant = userInfoMapper.getApplicantByUser(order.getUserId());
        if (null != applicant && null != applicant.getLevelId()) {
            System.out.println("说明有上级");
            Level level = levelMapper.selectLevel(applicant.getLevelId());
            //如果购买用户等级小于上级的等级 ，则让上级获得利益
            if (applicant.getLevelId() != 0 && userInfo.getRecomAward() < level.getRecomAward()) {
                System.out.println("让上级获取利益");
                b = new BigDecimal((level.getRecomAward() - userInfo.getRecomAward()) / 100);
                if (null != b) {
                    bounty = b.multiply(order.getOrderPrice());
                    applicant.setBounty(bounty);
                    int i = addBounty(order.getProNum(), userInfo, bounty);
                    if (i<0){
                        logger.error("[order][addBounty]上级添加用户获得金豆记录异常");
                        return -1;
                    }
                }
            }else {
                applicant.setBounty(null);
            }
            up=product.getRecomUp()*order.getOrderSpecs();
            applicant.setSumUp(up);
            //判断上级是否达到升级要求
            Integer m= this.upLevel(applicant.getSumUp() + up, applicant.getType());
            if (null!=m&&m!=-1){
                applicant.setLevelId(m);
            }
            //修改申请人的金豆
            x=userInfoMapper.update(applicant);
            System.out.println(x);
            if (x<0){
                logger.error("[order][update]上级用户修改升力值以及等级异常");
            }
        }
        return x;
    }

    //判断用户升力值是否达到升级要求
    private Integer upLevel(int up,int type){
        int x =-1;

        List<Level> ls = levelMapper.upLevel(type);

        for (Level l:ls){
            if (up>=l.getUpValue()){
                x=l.getLevelId();
            }
        }
        return x;

    }

    //添加一条金豆记录
    private int addBounty(String str, UserInfo userInfo, BigDecimal bountyMoney) {
        int n = -1;
        Bounty bounty = new Bounty();
        bounty.setBountyMoney(bountyMoney);

        bounty.setBountyId(CodecUtil.createId());
        bounty.setUserId(userInfo.getUserId());
        bounty.setProNum(str);
        bounty.setRecomAward(userInfo.getRecomAward());
        n = bountyMapper.insertSelective(bounty);
        return n;
    }



    @Override
    public BigDecimal bigMony(String userId) {
        return orderMapper.bigMony(userId);
    }

    /**
     * 购买产品的订单
     *
     * @param userId
     * @return
     */
    @Override
    public List<Order> listOrder(String userId) {

        List<Order> orders = orderMapper.listOrder(userId);

        return orders;
    }

    /**
     * 购买会员的订单
     *
     * @param
     * @return
     */
    @Override
    public List<Order> listLevel(String userId) {

        List<Order> orders = orderMapper.listLevel(userId);

        return orders;
    }

    @Override
    public int offlinePay(String orderId) {
        int i = orderMapper.updatePayPtate(orderId);
        if (i > 0) {
            Order order = orderMapper.selectByPrimaryKey(orderId);
            return this.addMill(order);

        }
        return -1;
    }


    @Override
    public OrderVoOne selectDetailsOne(Order order) {
        return orderMapper.selectDetailsOne(order);
    }

    @Override
    public OrderVoTwo selectDetailsTwo(Order order) {
        return orderMapper.selectDetailsTwo(order);
    }

    @Override
    public OrderVoThree selectDetailsTree(Order order) {
        return orderMapper.selectDetailsThree(order);
    }

    @Override
    public int delOrder(String orderId) {
        return orderMapper.deleteByPrimaryKey(orderId);
    }


}
